package com.love.zywanandroid.fragment

import android.Manifest
import android.app.Activity
import android.content.DialogInterface
import android.content.Intent
import android.provider.Settings
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.google.gson.Gson
import com.huantansheng.easyphotos.EasyPhotos
import com.huantansheng.easyphotos.models.album.entity.Photo
import com.love.zywanandroid.retrofit.RetrofitManager
import com.love.zywanandroid.retrofit.api.ApiService
import com.zat.mes.andrmes.R
import com.zat.mes.andrmes.base.BaseFragment
import com.zat.mes.andrmes.data.BaseResponse
import com.zat.mes.andrmes.data.LoginResultBean
import com.zat.mes.andrmes.dofun.main.vm.ApkModel
import com.zat.mes.andrmes.dofun.system.AboutActivity
import com.zat.mes.andrmes.dofun.system.UpdatePwdActivity
import com.zat.mes.andrmes.event.LoadingEventMessage
import com.zat.mes.andrmes.event.TokenEventMessage
import com.zat.mes.andrmes.global.CompanionCode.Companion.INSTALL_CODE_ME
import com.zat.mes.andrmes.global.CompanionType
import com.zat.mes.andrmes.retrofit.callback.MesCallBack
import com.zat.mes.andrmes.utils.*
import kotlinx.android.synthetic.main.fragment_me.*
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.json.JSONObject
import permissions.dispatcher.*
import retrofit2.Call
import retrofit2.Response
import top.zibin.luban.Luban
import top.zibin.luban.OnCompressListener
import java.io.File
import java.util.*

/**
 * @author zy
 * @date :2019-02-13 10:43
 * @description: 我的
 */
@RuntimePermissions
class MeFragment : BaseFragment(), View.OnClickListener {
    /**
     * app更新model
     */
    var apkModel: ApkModel? = null
    var updateManager: UpdateManager? = null

    /**
     * 点击事件
     */
    override fun onClick(v: View?) {
        when (v) {
            llBtnUpdatePwdMe -> {
                startFragmentActivity(Intent(context, UpdatePwdActivity::class.java))

            }
            llBtnClearMe -> {
                val size = GlideUtil.getCacheSize(context);
                GlideUtil.clearImageDiskCache(context)
                Toast.makeText(
                    context,
                    getString(R.string.me_clear_memory) + size,
                    Toast.LENGTH_LONG
                ).show()
            }
            btnMesMe -> {
                startFragmentActivity(Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS));

            }
            llBtnCheckVersoin -> {
                //版本更新
                checkAppVerWithPermissionCheck()
            }
            btnAboutMe -> {
                //关于我们
                startFragmentActivity(Intent(context, AboutActivity::class.java))
            }
            ivHeaderMe -> {
                //图片选择
                var builder = AlertDialog.Builder(context!!)
                    .setMessage("是否打开相册")
                    .setPositiveButton("是", DialogInterface.OnClickListener { dialog, which ->
                        EasyPhotos.createAlbum(this, true, GlideEngine.getInstance())
                            .setFileProviderAuthority("com.ntl.mes.andrmes.fileProvider")
                            .setOriginalMenu(false, true, null)
                            .setPuzzleMenu(false)
                            .setCleanMenu(false)
                            .start(101)
                    })
                    .setNegativeButton("否", null)
                builder.show()


            }
        }
    }


    var loginResultBean: LoginResultBean? = null
    override fun getViewId(): Int {
        return R.layout.fragment_me
    }

    override fun initData() {
        EventBus.getDefault().register(this)
        loginResultBean = Gson().fromJson(
            PreferencesUtil.getString(CompanionType.LOGIN_RESULT),
            LoginResultBean::class.java
        )
        tvNameMe.text = loginResultBean?.empname
        tvNoMe.text = loginResultBean?.empno
        if ("1" == loginResultBean?.sex) {
            tvSexMe.text = getString(R.string.man)
        } else {
            tvSexMe.text = getString(R.string.woman)
        }
        tvWorkShopMe.text = loginResultBean?.workShopname
        tvClassMe.text = loginResultBean?.classname
        tvPhoneMe.text = loginResultBean?.tel
        tvEmailMe.text = loginResultBean?.email
        GlideUtil.setHeader(context, loginResultBean?.img, ivHeaderMe)
        if (!TextUtils.isEmpty(loginResultBean?.birthday)) {
            try {
                var strBirth = ""
                strBirth = loginResultBean?.birthday?.substring(
                    2,
                    4
                ) + "/" + loginResultBean?.birthday?.substring(
                    4,
                    6
                ) + "/" + loginResultBean?.birthday?.substring(6, 8)
                tvBirthMe.text = strBirth
            } catch (e: Exception) {

            }
        } else {
            tvBirthMe.text = ""
        }
        apkModel = ViewModelProvider(this).get(ApkModel::class.java)
        apkModel?.getApkBean()?.observe(this, Observer {
            closeLoading()
            if (it == null) {
                Toast.makeText(context, getString(R.string.version_no_new), Toast.LENGTH_LONG)
                    .show()
            } else {
                //显示下载
                context?.let { it1 ->
                    AlertDialog.Builder(it1)
                        .setMessage(getString(R.string.version_new_content))
                        .setNegativeButton(getString(R.string.cancel), null)
                        .setPositiveButton(
                            getString(R.string.sure),
                            DialogInterface.OnClickListener { dialog, which ->
                                updateManager = UpdateManager(context, it.fileUrl, INSTALL_CODE_ME);
                            })
                        .show()
                }
            }
        })
    }

    override fun isOpenTitleBar(): Boolean {
        return false
    }

    override fun initView() {
        btnLogout.setOnClickListener {
            context?.let { it1 ->
                AlertDialog.Builder(it1)
                    .setMessage(getString(R.string.logout_sure_content))
                    .setNegativeButton(getString(R.string.cancel), null)
                    .setPositiveButton(
                        getString(R.string.sure),
                        DialogInterface.OnClickListener { dialog, which ->
                            logout()
                        })
                    .show()
            }

        }
        llBtnUpdatePwdMe.setOnClickListener(this)
        llBtnClearMe.setOnClickListener(this)
        btnMesMe.setOnClickListener(this)
        llBtnCheckVersoin.setOnClickListener(this)
        btnAboutMe.setOnClickListener(this)
        ivHeaderMe.setOnClickListener(this)
    }

    /**
     * 注销登录
     */
    fun logout() {
        showLoading()

        val jsonObject = JSONObject()
        jsonObject.put("EmpEnName", loginResultBean?.empEnName);
        val requestBody: RequestBody =
            RequestBody.create(RetrofitManager.JOSNTYPE, jsonObject.toString())
        RetrofitManager.apiService(ApiService::class.java).logout(requestBody).enqueue(object :
            MesCallBack<BaseResponse<String>>() {
            override fun onSuccessful(
                call: Call<BaseResponse<String>>?,
                response: Response<BaseResponse<String>>?
            ) {
                if (response?.body()?.success != null) {
                    if (response.body()?.success!!) {
                        //清除token corpid
                        PreferencesUtil.remove(CompanionType.LOGIN_RESULT)
                        PreferencesUtil.remove(CompanionType.TOKEN)
                        PreferencesUtil.remove(CompanionType.CORPID)
                        EventBus.getDefault().post(TokenEventMessage("logout"))
                    }
                } else {
                    getString(R.string.net_request_fail)
                }
            }


        })
    }

    @NeedsPermission(
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.WRITE_EXTERNAL_STORAGE
    )
            /**
             * app版本
             */
    fun checkAppVer() {
        showLoading()
        apkModel?.loadCheckVersion(
            context?.packageManager?.getPackageInfo(
                context?.packageName,
                0
            )?.versionCode.toString()
        )
    }

    @OnShowRationale(
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.WRITE_EXTERNAL_STORAGE
    )
    fun showRationale(request: PermissionRequest) {
        request.proceed();
        Log.e("permission", "OnShowRationale")
    }

    @OnPermissionDenied(
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.WRITE_EXTERNAL_STORAGE
    )
    fun onDenied() {
        checkAppVerWithPermissionCheck()
    }

    @OnNeverAskAgain(
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.WRITE_EXTERNAL_STORAGE
    )
    fun onNeverAskAgain() {
//        Toast.makeText(context, "请到设置打开存储权限", Toast.LENGTH_LONG).show()
        SystemActivityUtil.getAppDetailSettingIntent(context)
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        onRequestPermissionsResult(requestCode, grantResults)
    }

    fun installApk() {
        updateManager?.resultInstall()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    open fun onLoadingEvent(event: LoadingEventMessage?) { /* Do something */
        closeLoading()
    }

    override fun onDestroyView() {
        EventBus.getDefault().unregister(this)
        super.onDestroyView()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (Activity.RESULT_OK == resultCode) {
            //相机或相册回调

            //相机或相册回调
            if (requestCode == 101) {
                //返回对象集合：如果你需要了解图片的宽、高、大小、用户是否选中原图选项等信息，可以用这个
                val resultPhotos: ArrayList<Photo> =
                    data!!.getParcelableArrayListExtra(EasyPhotos.RESULT_PHOTOS)

                //返回图片地址集合时如果你需要知道用户选择图片时是否选择了原图选项，用如下方法获取
                val selectedOriginal =
                    data!!.getBooleanExtra(EasyPhotos.RESULT_SELECTED_ORIGINAL, false)
                val photo = resultPhotos[0]
                Log.e("photo", photo.size.toString())
                showLoading()
                Luban.with(context)
                    .load(File(photo.path))
                    .setTargetDir(context?.filesDir?.path)
                    .setCompressListener(object : OnCompressListener {
                        override fun onSuccess(file: File?) {
                            Log.e("file", file?.length().toString())
                            //开始上传
                            val requestFile =
                                RequestBody.create(MediaType.parse("image/*"), file)
                            val body: MultipartBody.Part = MultipartBody.Part.createFormData(
                                "pic",
                                System.currentTimeMillis().toString() + ".jpg",
                                requestFile
                            )
                            RetrofitManager.apiService(ApiService::class.java)
                                .postPic(body)
                                .enqueue(object : MesCallBack<BaseResponse<String>>() {
                                    override fun onSuccessful(
                                        call: Call<BaseResponse<String>>?,
                                        response: Response<BaseResponse<String>>?
                                    ) {
                                        var pic = response?.body()?.result
                                        Log.e("pic", pic)
                                        if (!TextUtils.isEmpty(pic)) {
                                            val loginResultBean = Gson().fromJson(
                                                PreferencesUtil.getString(CompanionType.LOGIN_RESULT),
                                                LoginResultBean::class.java
                                            )
                                            val json = JSONObject()
                                            json.put("empId", loginResultBean.empid)
                                            json.put("img", pic)
                                            val requestBody: RequestBody = RequestBody.create(
                                                RetrofitManager.JOSNTYPE,
                                                json.toString()
                                            )
                                            RetrofitManager.apiService(ApiService::class.java)
                                                .postEmpImg(requestBody)
                                                .enqueue(object :
                                                    MesCallBack<BaseResponse<String>>() {
                                                    override fun onSuccessful(
                                                        call: Call<BaseResponse<String>>?,
                                                        response: Response<BaseResponse<String>>?
                                                    ) {
                                                        closeLoading()

                                                        if (response?.body()?.success!=null && response?.body()?.success!!) {
                                                            //更换图片接口
                                                            loginResultBean?.img = pic.toString()
                                                            //保存登录后人员企业等信息
                                                            PreferencesUtil.saveValue(
                                                                CompanionType.LOGIN_RESULT,
                                                                Gson().toJson(loginResultBean)
                                                            )
                                                            GlideUtil.setHeader(
                                                                context,
                                                                loginResultBean?.img,
                                                                ivHeaderMe
                                                            )
                                                        }
                                                    }


                                                })

                                        }else{
                                            Toast.makeText(context,"上传失败",Toast.LENGTH_SHORT).show()
                                        }
                                    }


                                })

                        }

                        override fun onError(e: Throwable?) {
                        }

                        override fun onStart() {
                        }
                    })
                    .launch()

                return
            }
        }
    }
}